package com.bestv.utils.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by Henry on 14-5-30.
 */
public class StringIdConverter {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
    private MessageDigest md5Digest;

    public StringIdConverter() {
        try {
            md5Digest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            logger.error("No such algorithm.", e);
        }
    }

    private long hash(String value) {
        byte[] md5hash;
        synchronized (md5Digest) {
            md5hash = md5Digest.digest(value.getBytes(UTF8_CHARSET));
            md5Digest.reset();
        }

        long hash = 0L;
        for (int i=0; i<8; i++) {
            hash = hash << 8 | md5hash[i] & 0x00000000000000FFL;
        }
        return hash;
    }

    public long toLongId(String stringId) {
        return hash(stringId);
    }
}
